define([
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"static/app/hddc/hddcShpDataMapDisplay/hddShpDataDisplaymap",
	"static/app/hddc/hddccjcommon/hddccjCommon",
	"static/app/hddc/hddccjtask/tmap",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
    ],function(Util, Tool, SelectOrg, SearchBlock,hddShpDataDisplaymap,HddccjCommon){

    var sysPath =  getServer() + "/static/app/hddc/hddcShpDataMapDisplay";

    var hddcCjHistorypointsFormHtml = sysPath + "/views/hddcShpDataDisplayForm.html";
	var getHddcCjHistorypointsController = function(){
		return getServer() + "/hddc/hddcShpDataMapDisplay";
	};

	/**
	 * 页面初始化
	 */
	var init = function(){
		//alert(123);
        //initSearchBlock();
        //queryBtnBind();
		//initStartTimeTime();
		//initEndTimeTime();
		//HddccjCommon.initProjectSelect("projectName"); //添加页面项目名称下拉
		//initSingleTaskSelect("projectName", "taskName");
		//addProjectData();
		//createHddcCjHistorypointsGrid();

		$("#taskMapLi").css("display", "block");
		hddShpDataDisplaymap.initMap();
        initselectdDtaTypeSelectFrom();
		uploadFile();
		downloadFile();
        showDataExpress();
        changeDataTable(); //切换字段说明
        $("#test").on("click",function () {
            // hddcPointData.showData("1","3498cd7714a7469d9ed366c5b2e9b835");
            //hddcPointData.showData(1,"03ad1e97047d46ae80ff800fdd24e616");
        })

	};

	// 判断一个数组是否包含另一个数组
	var isContained = function (maxList,minList) {
		var newList = minList.filter(function (item) {
			return maxList.indexOf(item)>-1;
        })
		if(newList.length == minList.length)
			return true;
		else
			return false;
    }

    // 判断上传.dbf、.prj、.shp、.shx文件各一个
    var judgeIsOnce = function (list) {
		// ["dbf","prj","shp","shx"];
		var dbf = 0;var prj = 0;var shp = 0;var shx = 0;var sbn = 0;var sbx = 0;var xml = 0;
		$.each(list,function (idx,item) {
            if(item == 'dbf') dbf++;
            if(item == 'prj') prj++;
            if(item == 'shp') shp++;
            if(item == 'shx') shx++;
            if(item == 'sbn') sbn++;
            if(item == 'sbx') sbx++;
            if(item == 'xml') xml++;
        })
		if(dbf == 1 && prj == 1 && shp == 1 && shx == 1 && sbn < 2 && sbx < 2 && xml < 2) return true;
		else return false;
    }

    var judgeName = function (list) {
		var name = list[0];
		var result = list.filter(function (item) {
			return item == name;
        })
		if(result.length == list.length) return true;
		else return false;
    }

    var downloadFile = function () {
        $("#button-export").on("click", function () {
            var provinceCode = $("#provinceSelect").val();
            var cityCode = $("#citySelect").val();
            var areaCode = $("#areaSelect").val();
            var type = $("#selectdDtaType").val();
             window.location.href = getHddcCjHistorypointsController() + "/download?provinceCode="+provinceCode+"&cityCode="+cityCode+"&areaCode="+areaCode+"&type="+type;

            /*$.ajax({
                url: getHddcCjHistorypointsController() + "/download?provinceCode="+provinceCode+"&cityCode="+cityCode+"&areaCode="+areaCode+"&type="+type,
                contentType: "application/x-download",
                type: "GET",
                success: function (data) {
                    Util.alert(data);
                    // if(data == "成功"){
                    //     window.location.href = getHddcCjHistorypointsController() + "/download?provinceCode="+provinceCode+"&cityCode="+cityCode+"&areaCode="+areaCode+"&type="+type;
                    // }else{
                    //     Util.alert(data);
                    // }
                }
            });*/

        })
    }

	var uploadFile = function(){
        // 要上传的文件的后缀名数组
        var minList = [];
        // 要上传的文件的文件名数组
        var nameList = [];
        // var maxList = ["dbf","prj","shp","shx"];
		// 获取文件名
        $("#button-selectfile").on("change", function () {
            var uploadinputFiles = document.getElementById("button-selectfile").files;
            
            minList = [];
            minList.length=0;
			nameList=[];
			nameList.length=0;
            var text = "";
            for (var i = 0; i < uploadinputFiles.length; i++){
                console.log("uploading: " + uploadinputFiles[i].name);
                text += uploadinputFiles[i].name+"\n";
                // 获取这个文件的后缀名
                minList.push(uploadinputFiles[i].name.slice(uploadinputFiles[i].name.length-3,uploadinputFiles[i].name.length));
                nameList.push(uploadinputFiles[i].name.split(".")[0]);
                
            }
            $("#commentInfo").val(text);
		});

        $("#button-import").on("click", function () {
            var uploadinput = document.getElementById("button-selectfile");
            var type = document.getElementById("selectdDtaType");
            debugger
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            // }else if(!isContained(minList) || minList.length<4){
            }/*else if(type.value == 26){
            	//if($("#citySelect").val()=="嘉峪关市"){
				/!*if($("#citySelect").val()=="620200"){
					if (!$("#provinceSelect").val()||!$("#citySelect").val()){
						Util.alert('请选择省、市。');
						return;
					}
				}else if (!$("#provinceSelect").val()||!$("#citySelect").val()||!$("#areaSelect").val()){
                    Util.alert('请选择省、市、县。');
                    return;
				}*!/

			}*/
			else if (!$("#provinceSelect").val()||!$("#citySelect").val()){
				Util.alert('请选择省、市。');
				return;
			}else if(!judgeIsOnce(minList)){
                Util.alert('上传数量限制:.dbf、.prj、.shp、.shx文件各1个;.sbn、.sbx、.shp.xml文件至多一个。');
                return;
			}else if(!judgeName(nameList)){
                Util.alert("文件名请保持一致！");
                return;
			}else if(type.value == ""){
                Util.alert("请选择空间数据类型!");
                return;
			}
            var formData = new FormData();
            for(var i = 0; i < uploadinput.files.length; i++){
                formData.append('files', uploadinput.files[i]);
            }
            formData.append("provinceName", $("#provinceSelect option:selected").text()=="请选择"?null:$("#provinceSelect option:selected").text());
            formData.append("cityName", $("#citySelect option:selected").text()=="请选择"?null:$("#citySelect option:selected").text());
            formData.append("areaName", $("#areaSelect option:selected").text()=="请选择"?null:$("#areaSelect option:selected").text());
            formData.append("provinceCode", $("#provinceSelect").val());
            formData.append("cityCode", $("#citySelect").val());
            formData.append("areaCode", $("#areaSelect").val());
            formData.append("type", $("#selectdDtaType").val());
			//formData.append("type", "39");
            
            $.ajax({
                url: getHddcCjHistorypointsController() + "/upload",
				data:formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    uploadinput.value = null;
                    $("#provinceSelect").val(""),
                    $("#citySelect").val(""),
                    $("#areaSelect").val(""),
                    $("#selectdDtaType").val(""),
                    $("#commentInfo").val(""),
                    Util.alert(data);
                }
            });
        });
	}


	$("#taskoperatelab").on('shown.bs.tab', function (e) {
		$("#taskMapLi").css("display", "none");
		hddShpDataDisplaymap.initClearMap();
		initSearchBlock();
	});

	$("#taskMaplab").on('shown.bs.tab', function (e) {
		hddShpDataDisplaymap.initMap();
	});




	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
            createHddcCjHistorypointsGrid();
        });
        $("#btnReset").click(function () {
			$("#startTimeCondition").val("");
				$("#endTimeCondition").val("");
				$("#taskIdCondition").val("");
				$("#remarkCondition").val("");
			});
	};

	var replayData=null;
	window.replaydata = function(data){
		console.log(data);
		replayData=data;
		$("#taskMapLi").css("display", "block");
		$('#myTab a[href="#replayMap"]').tab('show');
		//hddcreplaymap.initMap(data);
	}



	var createHddcCjHistorypointsGrid= function() {
		var taskDatas=HddccjCommon.getAllTask();
        $("#hddcCjHistorypointsGrid").datagrid({
            url:getHddcCjHistorypointsController() + "/queryHddcCjHistorypointss",
			method:"GET",
            fitColumns: true,
            autoRowHeight: false,
            columns:[[
				{
					field:'ddd',
					title:'',
					width:'25%',
					align:'center',
					formatter:function(value,rowData){
						return '<a href="#" onclick="replaydata(\'' + rowData.lonlatArray + '\');"> '+'轨迹回放'+' </a> '
					}
				},
				{
					field:'startTime',
					title:'开始时间',
					width:'25%',
					align:'center',
				},
				{
					field:'endTime',
					title:'结束时间',
					width:'25%',
					align:'center',
				},
				{
					field:'taskId',
					title:'任务名称',
					width:'25%',
					align:'center',
					formatter:function(value,rowData){
						for(var i=0;i<taskDatas.length;i++){
							if(rowData.taskId==taskDatas[i].taskId){
								return taskDatas[i].taskName;
							}
						}
						return rowData.taskId;
					}
				},
            ]],
            toolbar: [
            	/*
            	{
                iconCls: 'fa fa-plus-circle',
                text:"添加",
                handler: function(){
                    addHddcCjHistorypoints();
                }
            },
            */{
                iconCls: 'fa fa-trash-o',
                text:"删除",
                handler: function(){
                    deleteHddcCjHistorypoints();
                }
            }],
            queryParams:{
				startTime: $("#startTimeCondition").val(),
				endTime: $("#endTimeCondition").val(),
				taskId: $("#taskIdCondition").val(),
				remark: $("#remarkCondition").val(),
            },
            pagination: true,
            pageSize: 10
        });
    };
	var formValidator = function(){
		$("#hddcCjHistorypointsForm").validate({
			rules : {
				startTime : {
					required : true,
				},
				endTime : {
					required : true,
				},
				taskId : {
					required : true,
				},
				userId : {
					required : true,
				},
			},
			messages : {
				startTime : {
					required : "开始时间不允许为空!",
				},
				endTime : {
					required : "结束时间不允许为空!",
				},
				taskId : {
					required : "任务Id不允许为空!",
				},
				userId : {
					required : "用户Id不允许为空!",
				},
			}
		});
	};
	var getHddcCjHistorypoints = function(id){
		$.ajax({
			url: getHddcCjHistorypointsController() + "/"+id,
			type: "get",
			success: function (data) {
				Tool.deserialize("hddcCjHistorypointsForm", data);
			}
		});
	};

	var addHddcCjHistorypoints = function () {
		var slidebar = Util.slidebar({
			url: hddcCjHistorypointsFormHtml,
			width: "580px",
			cache: false,
			close : true,
			afterLoad: function () {
				initStartTimeTimeDate();
				initEndTimeTimeDate();
				formValidator();
				$("#saveBtn").on("click", function () {
					if($("#hddcCjHistorypointsForm").valid()){
						var data = Tool.serialize("hddcCjHistorypointsForm");
						$.ajax({
							url: getHddcCjHistorypointsController()+"/save" ,
                            contentType:"application/json",
							data: JSON.stringify(data),
							type: "post",
							success: function (data) {
								Util.alert(data.message);
								slidebar.close();
                                createHddcCjHistorypointsGrid();
							}
						});
					}
				});
			}
		});
	};
	window._editHddcCjHistorypoints = function(hddcCjHistorypointsId) {
		var slidebar = Util.slidebar({
			url: hddcCjHistorypointsFormHtml,
			width: "580px",
			cache: false,
			close : true,
			afterLoad: function () {
				initStartTimeTimeDate();
				initEndTimeTimeDate();
				formValidator();
				getHddcCjHistorypoints(hddcCjHistorypointsId);
				$("#saveBtn").on("click", function () {
					if($("#hddcCjHistorypointsForm").valid()){
						var data = Tool.serialize("hddcCjHistorypointsForm");
						$.ajax({
							url: getHddcCjHistorypointsController()+"/update",
                            contentType:"application/json",
                            data: JSON.stringify(data),
							type: "post",
							success: function (data) {
								Util.alert(data.message);
								slidebar.close();
								createHddcCjHistorypointsGrid();
							}
						});
					}
				});
			}
		});
	};
    var initselectdDtaTypeSelectFrom = function () {
        $.ajax({
            url: getHddcCjHistorypointsController() + "/getValidDictItemsByDictCode/" + "shpDataMapDisplay",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("selectdDtaType");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }

				var mySelect1 = document.getElementById("selectdDtaType1");
				mySelect1.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect1.add(new Option(name, code));
				}
            }
        });
    };
	var deleteHddcCjHistorypoints = function() {
		var rows = $("#hddcCjHistorypointsGrid").datagrid("getSelections");
		if (rows == null || rows.length == 0) {
			Util.alert("请选择一行数据!");
			return;
		}
		Util.confirm("是否要删除选中的数据?", function() {
			var ids = "";
			$.each(rows, function(i, row){
				ids += row.uuid + ",";

			});
			ids = ids.substr(0,ids.length - 1);
			$.ajax({
				url: getHddcCjHistorypointsController()+"/delete" ,
				contentType:"application/json",
				data:  ids,
				type: "post",
				success: function (data) {
					createHddcCjHistorypointsGrid();
				}
			});
		}, function() {
			return;
		});

	};

	var changeDataTable = function () {
        $("#selectdDtaType").change(function () {
            var type = $("#selectdDtaType").val();
			createDataExpressGrid(type);
        });
		$("#selectdDtaType1").change(function () {
			var type = $("#selectdDtaType1").val();
			createDataExpressGrid(type);
		});
    }

	// 数据类型说明
    var showDataExpress = function () {
        $("#dataExpress").on("click",function () {
            var type = $("#selectdDtaType").val();

            if(type == "" || type == null){
                Util.alert("请选择空间数据类型!");
                return;
            }else{
                $("#dataExpressDiv").show();
                createDataExpressGrid(type);
			}
        })
        $("#dataExpressCloseBtn").on("click",function () {
            $("#dataExpressDiv").hide();
        })
    }
    var createDataExpressGrid= function(type) {
    	// console.log(data);
        $("#dataExpressGrid").datagrid({
            url:getServer() + "/static/app/hddc/hddcShpDataMapDisplay/json/"+type+".json",
            method:"GET",
            fitColumns: true,
            autoRowHeight: false,
            nowrap:false,
			fit:true,
            columns:[[
                {
                    field:'name',
                    //title:'字段名',
					title:'序号',
                    width:'22%',
                    align:'center',
                    formatter:function(value,rowData,rowIndex){
                        return rowIndex+1;
                    }
                },
                {
                    field:'type',
                    //title:'字段类型',
                    title:'数据类型',
                    width:'22%',
                    align:'center',
                },
                {
                    field:'mustWrite',
                    title:'是否必填',
                    width:'12%',
                    align:'center',
                },
                {
                    field:'cnName',
                    title:'注释',
                    width:'22%',
                    align:'center',
                },
                {
                    field:'example',
                    title:'示例',
                    width:'22%',
                    align:'center',
                }
            ]],
			rowStyler: function (index,row) {
            	if (type == 26 && row.cnName == '断层编号' || row.cnName == '断层名称' || row.cnName == '断层性质' || row.cnName == '最新活动时代')
            		return 'color:red'
			}

        });
    };

	return {
		init:init
	};
});